package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/17 19:08
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //添加订单
    @PostMapping("/add")
    public Result add(@RequestBody Map map) {
        /*前端发送过来请求,判断验证码是否正确
        获取前段传来的验证码*/
        String validateCode = (String) map.get("validateCode");

        /**
        从jedis中获取验证码
            1.1获取前段传来的电话号码
            1.2从数据库中获取验证码
        **/

        String telephone = (String) map.get("telephone");
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (validateCode == null || code == null || !validateCode.equals(code)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //调用service
        try {
            Result result = orderService.add(map);
            String param=result.getData().toString();
            if (result.isFlag()) {
                //发送短信
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,param);
                return result;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"预约失败");
        }
    }

    @PostMapping("/findById")
    public Result findById(Integer id) {
        Map map= null;
        try {
            map = orderService.getById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
